<template>
  <div id="app">
    <div class="layout-wrapper">
      <div class="header">
        <div class="page-title">位置</div>
        <div id="path">{{ basePath }}</div>
        <div class="header-mobile-buttons">
          <span class="search-bar-btn"><i class="bi bi-search"></i></span>
        </div>

        <el-button
          mini
          type="primary"
          class="goback"
          :disabled="gobackStatus"
          @click="backOne"
          ><i class="el-icon-back"></i>返回上一级</el-button
        >
        <div class="col-md-3 currIP" style="margin-left: auto">
          当前IP：{{ host }}
        </div>
      </div>
      <div class="content">
        <div class="card mb-4">
          <div class="card-body">
            <form>
              <div class="row g-3">
                <div class="col-md-4 col-lg-2">
                  <el-select
                    v-model="jumpToIp"
                    placeholder="请选择"
                    @input="changeLink"
                  >
                    <el-option value="21.47.45.3">21.47.45.3</el-option>
                    <el-option value="21.47.45.4">21.47.45.4</el-option>
                    <el-option value="21.47.45.5">21.47.45.5</el-option>
                    <el-option value="21.47.45.6">21.47.45.6</el-option>
                    <el-option value="21.47.45.7">21.47.45.7</el-option>
                    <el-option value="21.47.45.8">21.47.45.8</el-option>
                    <el-option value="21.47.45.11">21.47.45.11</el-option>
                  </el-select>
                </div>
                <div class="col-md-4 col-lg-2">
                  <el-input
                    type="text"
                    placeholder="请输入文件名进行搜索"
                    v-model="matchKey"
                  ></el-input>
                </div>
                <div class="col-md-4 col-lg-1">
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="search('')"
                    >搜索</el-button
                  >
                </div>
              </div>
            </form>
          </div>
        </div>

        <el-table
          :data="tableData"
          style="width: 100%"
          row-click="handleRowClick"
          row-dblclick="rowDblclick"
        >
          <el-table-column width="50">
            <template v-slot="scope">
              <i class="el-icon-folder" v-if="!scope.row.fileType"></i>
              <i class="el-icon-document" v-else></i>
            </template>
          </el-table-column>
          <el-table-column prop="fileName" label="名称" align="center">
            <template v-slot="scope">
              <a
                class="foldername"
                @click="search(scope.row.fileName)"
                v-if="!scope.row.fileType"
                >{{ scope.row.fileName }}</a
              >
              <span
                v-else
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
                ><span>{{ scope.row.fileName }}</span
                ><i
                  @click="downloadFile(scope.row.fileName)"
                  class="el-icon-download"
                  alt="下载"
                ></i
              ></span>
            </template>
          </el-table-column>
          <el-table-column
            prop="lastModifyTime"
            label="修改日期"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="name" label="类型" align="center">
            <template v-slot="scope">
              <span v-if="!scope.row.fileType">文件夹</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="大小" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.size }}</span>
              <!-- <el-button
                class="downloadBtn"
                size="mini"
                type="success"
                v-if="scope.row.fileType"
                @click="downloadFile(scope.row.fileName)"
                ><i class="el-icon-download"></i>下载</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog
      title="正在下载，请等待"
      :visible.sync="fileDown.loadDialogStatus"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="20%"
    >
      <div style="text-align: center">
        <el-progress
          type="circle"
          :percentage="fileDown.percentage"
        ></el-progress>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "App",
  data() {
    return {
      basePath: "",
      foldersList: [],
      fileList: [],
      fileDown: {
        loadDialogStatus: false, //弹出框控制的状态
        percentage: 0, //进度条的百分比
      },
      matchKey: "",
      tableData: [],
      host: "192.168.219.56",
      gobackStatus: true,
      jumpToIp: "21.47.45.3",
    };
  },

  methods: {
    search(path) {
      this.tableData = [];
      path = path || "";
      var formData = new URLSearchParams();
      if (this.basePath === "/") {
        this.basePath = "/" + path;
      } else {
        this.basePath = this.basePath + "/" + path;
      }
      formData.append("path", this.basePath);
      formData.append("matchKey", this.matchKey);
      axios
        .post(this.baseUrl, formData)
        .then((res) => {
          if (res.data.code !== 200) {
            alert("请求失败！");
            return false;
          }
          let data = res.data.data;
          let foldersList = data.filter((p) => {
            return p.fileType === 0;
          });
          let fileList = data.filter((p) => {
            return p.fileType === 1;
          });
          this.tableData = [...foldersList, ...fileList];
        })
        .catch((error) => {
          console.log(error);
        });
      this.matchKey = "";
      if (this.basePath !== "/") {
        this.gobackStatus = false;
      }
    },
    //返回上一级
    backOne() {
      let path = this.basePath.split("/");
      path.pop();
      this.basePath = path.join("/");
      this.search();
      if (this.basePath.slice(-1, 0) === "") {
        this.basePath = this.basePath.slice(0, -1);
      }
      if (this.basePath === "") {
        this.basePath = "/";
        this.gobackStatus = true;
      }
    },

    //下载文件
    downloadFile(fileName) {
      this.fileDown.loadDialogStatus = true;
      this.fileDown.percentage = 0;

      const instance = this.initInstance();

      instance({
        url: this.downloadUrl,
        method: "GET",
        withCredentials: true,
        params: {
          path: this.basePath + "/" + fileName,
        },
        responseType: "blob",
      })
        .then((response) => {
          this.fileDown.loadDialogStatus = false;
          const content = response.data;
          if (content.size == 0) {
            this.loadClose();
            this.$alert("下载失败");
            return;
          }
          const blob = new Blob([content], {
            type: "application/octet-stream",
          });
          const downloadLink = document.createElement("a");
          downloadLink.href = URL.createObjectURL(blob);
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);
        })
        .catch((error) => {
          this.fileDown.loadDialogStatus = false;
          console.error("Error downloading file:", error);
        });
    },

    initInstance() {
      var _this = this;
      this.fileDown.source = axios.CancelToken.source();
      const instance = axios.create({
        onDownloadProgress: function (e) {
          const load = e.loaded;
          const total = e.total;
          const progress = (load / total) * 100;
          if (progress > _this.fileDown.percentage) {
            _this.fileDown.percentage = Math.floor(progress);
          }
          if (progress == 100) {
            _this.fileDown.loadDialogStatus = false;
          }
        },
      });
      return instance;
    },
    changeLink(link) {
      this.host = link;
      this.basePath = "";
      this.gobackStatus = true;
      this.search();
    },
  },
  created() {
    this.search();
  },
  computed: {
    baseUrl() {
      return "http://" + this.host + ":80/api/file/getDir";
    },
    downloadUrl() {
      return "http://" + this.host + ":80/api/file/download";
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
.goback {
  margin-left: 50px !important;
}
.foldername {
  color: cornflowerblue;
  cursor: pointer;
}
.downloadBtn {
  margin-left: 10px !important;
}
.el-icon-download {
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
  &:hover {
    color: cornflowerblue;
  }
}
.row {
  gap: 10px;
}
.currIP {
  font-size: 16px;
  font-weight: bold;
}
</style>
